﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Security.Claims;
using System.Security.Principal;

namespace SiteApp.Web.Controllers.Authorization
{
    //优先级1：权限过滤器：它在Filter Pipleline中首先运行，并用于决定当前用户是否有请求权限。如果没有请求权限直接返回。
    public class MyAuthorization : IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            try
            {
                var claimsIdentity = new ClaimsIdentity(new Claim[] {
                 new Claim("IsAuthenticated","false")
                }, "Basic");
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                #region app windows 硬件端
               
                var key = context.HttpContext.Request.Headers["siteapp.web"];
                if (!string.IsNullOrWhiteSpace(key) && key.ToString() == "qDV0Dyovqz+76NoaeCXucw==")
                {
                        claimsIdentity = new ClaimsIdentity(new Claim[] {
                     new Claim("IsAuthenticated","true")
                    }, "Basic");
                        claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                }

                key = context.HttpContext.Request.Headers["siteapp.workservice"];
                if (!string.IsNullOrWhiteSpace(key) && key.ToString() == "r/UTR12IhajUhXHdyAT11cr2jgZQv2y2xDCNokmuTzk=")
                {
                        claimsIdentity = new ClaimsIdentity(new Claim[] {
                     new Claim("IsAuthenticated","true")
                    }, "Basic");
                        claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                }

                key = context.HttpContext.Request.Headers["siteapp.client"];
                if (!string.IsNullOrWhiteSpace(key) && key.ToString() == "ZZa+K4RC2KBPfkNCcwf49g==")
                {
                    claimsIdentity = new ClaimsIdentity(new Claim[] {
                     new Claim("IsAuthenticated","true")
                    }, "Basic");
                    claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                }
                #endregion

                context.HttpContext.User = claimsPrincipal;

            }
            catch (Exception e)
            {

                //  log.Info(e);
            }

        }
    }

    public class MyClaimsPrincipal : ClaimsPrincipal
    {
        public MyIdentity Identity { get; set; }
    }
    public class MyIdentity : IIdentity
    {
        //证件名称
        public string Name { get; set; }

        // 用于标识证件的载体类型。
        public string AuthenticationType { get; set; }

        //是否是合法的证件。
        public bool IsAuthenticated { get; set; }
    }


}
